package com.zjk.storage.core.entity;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Optional;


@Getter
public class CustomMultipartFile implements MultipartFile {

    private String name;
    private String originalFilename;
    private String contentType;
    private byte[] bytes;

    public CustomMultipartFile(String name, String originalFilename, String contentType, byte[] byteArray) {
        this.name = name;
        this.originalFilename = originalFilename;
        this.contentType = contentType;
        this.bytes = Optional.ofNullable(byteArray).orElse(new byte[0]);
    }

    public CustomMultipartFile(String name, InputStream in) {
        this(name,"",null, IoUtil.readBytes(in));
    }

    public CustomMultipartFile(String name, byte[] bytes) {
        this(name,"",null,bytes);
    }

    public CustomMultipartFile(String name, String originalFilename, String contentType, FileInputStream fileInputStream) {
        this(name,originalFilename,contentType,IoUtil.readBytes(fileInputStream));
    }


    @Override
    public boolean isEmpty() {
        return this.bytes.length==0;
    }

    @Override
    public long getSize() {
        return this.bytes.length;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(this.bytes);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        FileUtil.writeBytes(this.bytes,dest);
    }
}
